package com.centon.auto_code.datasources;

import com.centon.auto_code.datasources.multisource.MultiDataSource;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration("autoCodeDataSourceConfig")
@MapperScan(basePackages = "com.yushang.e_commerce.e_commerce.mapper", sqlSessionTemplateRef  = "autoCodeSqlSessionTemplate")
public class AutoCodeDataSource {

    @ConfigurationProperties(prefix = "spring.multisource")
    @Bean(name = "autoCodeDataSource")
    public DataSource autoCodeDataSource() {
        return new MultiDataSource();
    }

    @Bean(name = "autoCodeSqlSessionFactory")
    public SqlSessionFactory autoCodeSqlSessionFactory(@Qualifier("autoCodeDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setTypeAliasesPackage("com.centon.auto_code.domain");
        bean.setDataSource(dataSource);
        Properties mProperties = new Properties();
        mProperties.put("Oracle", "oracle");
        mProperties.put("MySQL", "mysql");
        mProperties.put("SQL Server", "sqlserver");
        mProperties.put("DB2", "db2");
        VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        databaseIdProvider.setProperties(mProperties);
        bean.setDatabaseIdProvider(databaseIdProvider);
        return bean.getObject();
    }

    @Bean(name = "autoCodeTransactionManager")
    public DataSourceTransactionManager autoCodeTransactionManager(@Qualifier("autoCodeDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "autoCodeSqlSessionTemplate")
    public SqlSessionTemplate autoCodeSqlSessionTemplate(@Qualifier("autoCodeSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}